package utils

import (
	"context"
	"errors"
	"fmt"
	"gin-template/config"
	"gin-template/global"
	"time"

	"github.com/golang-jwt/jwt/v5"
	"golang.org/x/crypto/bcrypt"
)

func BcryptPassword(password string) (string, error) {
	hash, err := bcrypt.GenerateFromPassword([]byte(password), 9)
	if err != nil {
		return "", err
	}
	return string(hash), nil
}

func GenerateJWT(username string) (string, error) {
	// 解析token过期时间
	duration, err := time.ParseDuration(config.AppConfig.Jwt.ExpiresTime)
	if err != nil {
		duration = 24 * time.Hour
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"username": username,
		"exp":      time.Now().Add(duration).Unix(),
	})

	signedToken, err := token.SignedString([]byte(config.AppConfig.Jwt.SigningKey))

	return signedToken, err
}

func CheckPwd(bcryptPassword string, password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(bcryptPassword), []byte(password))
	return err == nil
}

func ParseJWT(tokenString string) (string, error) {
	if len(tokenString) > 7 && tokenString[:7] == "Bearer " {
		tokenString = tokenString[7:]
	}

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("unexpected Signing Method")
		}
		return []byte(config.AppConfig.Jwt.SigningKey), nil
	})

	if err != nil {
		return "", err
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		username, ok := claims["username"].(string)
		if !ok {
			return "", errors.New("username claim is not a string")
		}

		// 单会话登录
		if config.AppConfig.App.SingleSessionLogin {
			redis_token, err := global.RedisDB.Get(context.Background(), username).Result()
			fmt.Println(redis_token)
			fmt.Println(tokenString)
			if err != nil {
				return "", err
			}
			if redis_token != tokenString {
				return "", errors.New("token is Lose effectiveness")
			}
		}

		return username, nil
	}

	return "", err
}
